package com.ys.controller.api.sys;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.DtreeSqlDto;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.YsMenu;
import com.ys.enume.sys.YsColEnum;
import com.ys.enume.sys.YsMenuEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.CommonApiService.ToFormDto;
import com.ys.service.sys.YsColService;
import com.ys.service.sys.YsMenuService;
import com.ys.util.excel.ReadExcel;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/api/inter/ysMenu")
public class ApiInterYsMenuController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<YsMenu> commonApiService;
	@Autowired
	private YsColService ysColService;
	@Autowired
	private YsMenuService ysMenuService;

//	@RequiresPermissions("tsDictionaryForModule:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(
			@ModelAttribute YsMenu cond,
			Long menuId,
			String orderby
			){
		
		if (menuId != null) {
			YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
			if (ysMenu.getLev() == YsMenuEnum.Lev.ONE.value) {
				cond.addLeftJoin("YS_Menu B on B.Id = A.Pid")
					.where("B.Pid = " + menuId);
			} else if (ysMenu.getLev() == YsMenuEnum.Lev.TWO.value) {
				cond.setPid(menuId);
			} else {
				cond.setId(menuId);
			}
		}

		cond.setOrderby("A.Lev asc,A.SortNo asc");
		
		cond.addLeftJoin("YS_Menu C ON C.Id = A.Pid")
			.addField("C.Name pname");
		
		
		return commonApiService.searchLay(cond);
	}
	
	@RequestMapping("/dtree")
    @ResponseBody
	public DtreeSqlDto dtree(Model model, HttpServletRequest request, HttpServletResponse response
			){
		return ysMenuService.dtree();
	}
	
	/*
	 * 彻底删除
	 */
	@PostMapping("/deleteTrue")
	@ResponseBody
	public R deleteTrue(HttpServletRequest request, HttpServletResponse response,
			Long id) {
		return ysMenuService.deleteTrue(id);
	}
	
	/**
	 * 新增
	 */
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return ysMenuService.add(params);
	}
	
	/**
	 * 修改
	 */
	@PostMapping("/edit")
    @ResponseBody
	public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return ysMenuService.edit(params);
	}
	
	/**
	 * 修改上级
	 */
	@PostMapping("/move")
    @ResponseBody
	public R move(Long id, Long pid){
		return ysMenuService.move(id, pid);
	}
	
	/**
	 * 调整顺序
	 */
	@PostMapping("/resort")
    @ResponseBody
	public R resort(Model model, HttpServletRequest request, HttpServletResponse response,
			String rows){
		return ysMenuService.resortMenu(rows);
	}
	
	/**
	 * 调整字段顺序
	 */
	@PostMapping("/resortCol")
    @ResponseBody
	public R resortCol(
			Integer sortType, // 类型：空或1(前台和表单字段顺序)2(字段导入顺序)3(子列表字段)4(子列表按钮)5(菜单按钮)
			String rows){
		return ysMenuService.resortCol(rows, sortType);
	}
	
	/**
	 * 设置
	 */
	@PostMapping("/settingBase")
    @ResponseBody
	public R settingBase(HttpServletRequest request,
			Long id,
			String nameShiroAuth,
			String templetType,
			String pathSelfDefine,
			String pathGridRequest, String pathGridEditRequest, String pathGridExportRequest,
			String pathCommitAdd, String pathCommitEdit, String pathCommitDelete,
			Long flowModelId, String pathFlowPass, String pathFlowRefuse, String pathFlowInit,
			String preCode, String connectCode, Integer startNo,
			Long gridId,
			Long rowClickGridId){
		return ysMenuService.settingBase(id, nameShiroAuth, templetType, pathSelfDefine, pathGridRequest, pathGridEditRequest, pathGridExportRequest,
				pathCommitAdd, pathCommitEdit, pathCommitDelete,
				flowModelId, pathFlowPass, pathFlowRefuse, pathFlowInit,
				preCode, connectCode, startNo, gridId, rowClickGridId);
	}

    @PostMapping("/uploadAndReadExcelBatchImport")
    @ResponseBody
	public R uploadAndReadExcelBatchImport(@RequestParam("file") MultipartFile uploadfile) throws Exception {
    	

		try {
			InputStream fileInputStream = uploadfile.getInputStream();
//	        BufferedInputStream bis = new BufferedInputStream(fileInputStream);
			
			// 文件初始名
			String sourceFilename = uploadfile.getOriginalFilename();
	    	if (!sourceFilename.endsWith(".xlsx")) {
				return R.error("请按照模板xlsx进行导入");
			}
			List<List<String>> data = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			
			List<TableDto.RowDto> rows = new ArrayList<TableDto.RowDto>();
			if (rows != null && rows.size() > 300) {
				return R.error("导入数量不能超过300条");
			}
			for (int i = 1; data != null && i < data.size(); i++) {
				List<String> row = data.get(i);
				TableDto.RowDto rowDto = new TableDto.RowDto(row.get(0), row.get(1), row.get(2), row.get(3), row.get(4), row.get(5),
						row.get(6), row.get(7), row.get(8), row.get(9), row.get(10), row.get(11), row.get(12), row.get(13), row.get(14), row.get(15),
						row.get(16), row.get(17), row.get(18), row.get(19), row.get(20), row.get(21), row.get(22), row.get(23), row.get(24), row.get(25),
						row.get(26), row.get(27), row.get(28), row.get(29), row.get(30), row.get(31), row.get(32), row.get(33), row.get(34), row.get(35),
						row.get(36), row.get(37), row.get(38), row.get(39), row.get(40), row.get(41), row.get(42), row.get(43), row.get(44), row.get(45),
						row.get(46), row.get(47));
				rows.add(rowDto);
			}
			TableDto dto = new TableDto(rows);
			return R.ok(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
	}
    
	@Data
	@AllArgsConstructor
	public static class TableDto{
		private List<RowDto> rows; // 货件清单数组
		
		@Data
		@AllArgsConstructor
		public static class RowDto {
			private String moduleTable; // 
			private String fieldName; // 
			private String fieldAlias; // 
			private String fields; // 
			private String fieldFrontTop; // 
			private String fieldFrontTemplet; // 
			private String fieldFrontType; // 
			private String fieldMatched; // 
			private String fieldSearchType; // 
			private String fieldFrontSave; // 
			private String fieldFrontShow; // 
			private String fieldFrontAlign; // 
			private String fieldFrontWidth; // 
			private String fieldFrontHeight; // 
			private String fieldFrontConditions; // 
			private String fieldFrontConditionsType; // 
			private String fieldFrontConditionsField; // 
			private String fieldFrontConditionsFixed; // 
			private String fieldFrontConditionsDefault; // 
			private String fieldFrontTotal; // 
			private String fieldDataLimit; // 
			private String fieldStandard; // 
			private String fieldFrontRequired; // 
			private String fieldFrontOrder; // 
			private String fieldFrontTopOrder; // 
			private String fieldFrontEdit; // 
			private String fieldFrontHidden; // 
			private String fieldFrontHiddenList; // 
			private String fieldFrontHiddenCallIn; // 
			private String fieldFrontFixed; // 
			private String fieldFrontImport; // 
			private String fieldFrontTopSize; // 
			private String fieldExceptEdit; // 
			private String fieldPopupShow; // 
			private String fieldPopupEdit; // 
			private String fieldFrontExtend1; // 
			private String fieldFrontExtend2; // 
			private String fieldFrontExtend3; // 
			private String fieldid; // 
			private String fieldType; // 
			private String fieldLength; // 
			private String fieldKey; // 
			private String fieldNull; // 
			private String fieldValue; // 
			private String fieldFrontValue; // 
			private String guid; // 主键ID
			private String createTime; // 
			private String info; // 
		}
	}
	
	/**
	 * 批量新增字段
	 */
	@PostMapping("/batchAddCol")
	@ResponseBody
	public R batchAddCol(HttpServletRequest request,
			String subData){
		
		JSONArray detailJA = JSON.parseArray(subData);
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject JO = detailJA.getJSONObject(i);
			Long menuId = JO.getLong("menuId");
			String code = JO.getString("code");
			String name = JO.getString("name");
			Integer authType = YsColEnum.AuthType.ALL.value;
			Integer frontFixed = YsColEnum.FrontFixed.NO.value;
			Integer frontWidth = 160;
			Integer sortNo = 999;
			String frontType = YsColEnum.FrontType.TEXT.value;
			Integer frontShow = YsColEnum.FrontShow.SHOW.value;
			Integer frontEdit = YsColEnum.FrontEdit.NO.value;
			Integer frontConditionState = YsColEnum.FrontConditionState.NO.value;
			String frontConditionType = YsColEnum.FrontConditionType.TEXT.value;
			String frontConditionRangeType = YsColEnum.FrontConditionRangeType.SYSTEM.value;
			String frontConditionCode = null;
			String frontConditionDefault = null;
			Integer frontExport = YsColEnum.FrontExport.SHOW.value;
			ysColService.add(menuId, code, name, authType, frontFixed, frontWidth, sortNo, frontType, frontShow, frontEdit, frontConditionState, frontConditionType, frontConditionRangeType, frontConditionCode, frontConditionDefault,frontExport);
		}
		return R.ok();
	}
	
	/**
	 * 获取导入字段
	 */
	@PostMapping("/importConfig")
    @ResponseBody
	public R importConfig(Model model, HttpServletRequest request, HttpServletResponse response,
			Long menuId){
		return ysMenuService.importConfig(menuId);
	}
	
	/**
	 * 获取表单HTML
	 * @throws Exception 
	 */
	@PostMapping("/getFormHTML")
    @ResponseBody
	public R getFormHTML(String ids) throws Exception{
		TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("form-html-template").queryFirst();
		String html = tbStaticConfig.getHypeText();
		
		ToFormDto formDto = commonApiService.getFormDto(ids);
		
		html = html.replace("_YS_REPLACE_DTO",
				JSON.toJSONString(formDto))
				.replace("[{", "[" + "\n" + "{")
				.replace("},", "}," + "\n")
				.replace("}]", "}" + "\n" + "]" + "\n");
		GetFormHTMLDto dto = new GetFormHTMLDto(html);
		return R.ok(dto);
	}
	@Data
	@AllArgsConstructor
	public static class GetFormHTMLDto{
		private String html;
		
	}
	
}
